<!--
 * @Description:
 * @Author:
 * @Date: 2020-05-15 14:58:56
 * @LastEditors  : liuyi
 * @LastEditTime : 2020-05-15 17:42:12
 -->
<template>
  <div
    id="processApproveComponents"
    v-loading="tableLoating"
    class="main_page"
  >
    <el-card
      class="process-card"
      style="height: 70px"
    >
      <el-row :gutter="8">
        <el-col style="text-align: center;">
          <font class="processTitle">
            <font style="margin-left:10px;">
              {{ processName }}
            </font>
          </font>
        </el-col>
      </el-row>
    </el-card>
    <el-card
      class="process-card"
      style="margin-top: 1px;height: calc(100% - 142px); overflow-y: auto"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="业务表单"
          name="form"
        >
          <el-collapse
            v-if="showHis"
            v-model="collapseList"
          >
            <template v-if="processData.type == 'handle'">
              <el-collapse-item
                v-for="(item,index) in formList"
                :key="index"
                :name="index"
              >
                <template
                  v-if="index == 0"
                  slot="title"
                >
                  <span style="font-size: 14px;font-weight: 500">
                    节点名称：{{ item.taskName }}
                  </span>
                  <span
                    style="font-size: 14px;
                  font-weight: 500;
                  display: block;
                  position: absolute;
                  width: 50%;
                  text-align: right;
                  right: 40px;"
                  >
                    {{ processData.name || user.name }} 在 {{ dateFormat(item.START_TIME_) }} 发起
                  </span>
                </template>
                <template
                  v-else
                  slot="title"
                >
                  <span style="font-size: 14px;font-weight: 500">
                    节点名称：{{ item.taskName }}
                  </span>
                  <span
                    v-if="!item.isCurrNode"
                    style="font-size: 14px;
                  font-weight: 500;
                  display: block;
                  position: absolute;
                  width: 50%;
                  text-align: right;
                  right: 40px;"
                  >
                    {{ item.name }} 在 {{ dateFormat(item.END_TIME_) }} 处理
                  </span>
                </template>
                <generate-from
                  v-if="item.isCurrNode"
                  ref="form1"
                  :json-data="item.formDataConfig"
                  @getFormData="getFormData"
                />
                <generate-from
                  v-else
                  :json-data="item.formDataConfig"
                  :form-data="item.formData"
                />
              </el-collapse-item>
            </template>
            <template v-else>
              <el-collapse-item
                v-for="(item,index) in formList"
                v-show="!item.isCurrNode"
                :key="index"
                :name="index"
              >
                <template
                  v-if="index == 0"
                  slot="title"
                >
                  <span style="font-size: 14px;font-weight: 500">
                    节点名称：{{ item.taskName }}
                  </span>
                  <span
                    style="font-size: 14px;
                    font-weight: 500;
                    display: block;
                    position: absolute;
                    width: 50%;
                    text-align: right;
                    right: 40px;"
                  >
                    {{ processData.name || user.name }} 在 {{ dateFormat(item.START_TIME_) }} 发起
                  </span>
                </template>
                <template
                  v-else
                  slot="title"
                >
                  <span style="font-size: 14px;font-weight: 500">
                    节点名称：{{ item.taskName }}
                  </span>
                  <span
                    v-if="!item.isCurrNode"
                    style="font-size: 14px;
                    font-weight: 500;
                    display: block;
                    position: absolute;
                    width: 50%;
                    text-align: right;
                    right: 40px;"
                  >
                    {{ item.name }} 在 {{ dateFormat(item.END_TIME_) }} 处理
                  </span>
                </template>
                <generate-from
                  v-if="!item.isCurrNode"
                  :form-data="item.formData"
                  :json-data="item.formDataConfig"
                />
              </el-collapse-item>
            </template>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane
          label="业务流程"
          name="process"
          lazy
        >
          <detail
            :process-obj="processData"
            :form-list="formList"
            type="approve"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-card
      style="margin-top: 1px;height: 70px"
      :body-style="{ 'text-align': 'center' }"
    >
      <el-button
        v-if="processData.type == 'handle'"
        type="primary"
        size="mini"
        style="margin-right:100px;bottom: 0px"
        @click="startTaskProcess"
      >
        提交
      </el-button>
      <el-button
        v-if="isRefill"
        type="primary"
        size="mini"
        style="margin-right:100px;bottom: 0px"
        @click="stopTaskProcess"
      >
        终止流程
      </el-button>
      <el-button
        size="mini"
        @click="returnCreateTask"
      >
        返回
      </el-button>
    </el-card>
  </div>
</template>
<script>
import generateFrom from '@/components/Form/ext/GenerateForm'
import detail from '../components/detail'
import formatDate from '@/utils/date';
import { getTaskList,getProcessDefinitionXml,submitProcess,delProcessInst } from '@/api/bpmn/bpmn'
const convert = require('xml-js')
import _ from 'lodash'
const getFormList = (list,result = []) => {
  list.forEach(item => {
    if (item.hasOwnProperty('attributes') && item.attributes.hasOwnProperty('camunda:formKey')) {
      result.push(item)
    }
    if (item.hasOwnProperty('elements')) {
      return getFormList(item.elements,result)
    }
  })
  return result
}
export default {
  components: { generateFrom,detail },
  data() {
    return {
      formList:[],
      showHis:false,
      tableLoating:false,
      jsonFormData:{
        'list': [],
        'config': {
          'labelWidth': 100,
          'labelPosition': 'right',
          'tableName': '',
          'size': 'mini'
        }
      },
      processData:{},
      activeName:'form',
      returnType:'check_process',
      processName:'',
      collapseList:[],
      procInstId:'',
      currNode:'',
      startNodeForm:'',
      currNodeKey:'',
      procDefId:'',
      isRefill:false,
      user:JSON.parse(sessionStorage.getItem('user')),
      xmlJson: null,
      element: null,
      processInfos: [],
      selectTask: null
    };
  },
  created() {
    this.tableLoating = true
    if (this.$route.params.data){
      sessionStorage.setItem('currProcessData', JSON.stringify(this.$route.params.data))
    }
    if (this.$route.params.type){
      this.returnType = this.$route.params.type
    }
    this.processData = JSON.parse(sessionStorage.getItem('currProcessData'))
  },
  mounted() {
    if (this.processData) {
      this.procInstId = this.processData.procInstId
      this.procDefId = this.processData.procDefID
      this.processName = this.processData.process_name
      if (this.procDefId) {
        this.initDiagram()
      }
    }
  },
  methods: {
    dateFormat(date){
      return formatDate(new Date(date),'yyyy-MM-dd hh:mm:ss')
    },
    handleClick(){},
    startTaskProcess(){
      this.$refs.form1[0].handleSubmit()
    },
    stopTaskProcess(){
      const self = this
      this.tableLoating = true
      delProcessInst(this.procInstId).then(res =>{
        console.log('res:', res)
        this.tableLoating = false
        self.$message({
          message: '流程终止成功',
          type: 'success',
          duration: 1500
        })
        this.$router.push({
          name: this.returnType
        });
      })
    },
    returnCreateTask(){
      this.$router.push({
        name: this.returnType
      });
    },
    getFormData(data){
      const self = this
      this.tableLoating = true
      data = JSON.parse(data)
      const form = {
        variables:{
        },
        businessKey:'eps'
      }
      for(let prop in data){
        form.variables[prop] = {
          'value':data[prop]
        }
      }
      const option = {
        taskId:this.currNode.taskId,
        form:form
      }
      submitProcess(option).then(() =>{
        this.tableLoating = false
        self.$message({
          message: '流程处理成功',
          type: 'success',
          duration: 1500
        })
        this.$router.push({
          name: this.returnType
        });
      }).catch(() =>{
        this.tableLoating = false
        self.$message({
          message: `发送流程-${this.processData.name}-失败`,
          type: 'error',
          duration: 1500
        })
      })
    },
    initDiagram() {
      const self = this
      if (!this.procDefId) {
        return
      }
      getProcessDefinitionXml(this.procDefId).then(res => {
        self.xmlJson = JSON.parse(convert.xml2json(res.bpmn20Xml))
        const result = getFormList(self.xmlJson.elements)
        const query = {
          'instId': this.procInstId
        }
        getTaskList(query).then(res =>{
          // 返回结果分组

          const dd = res.data.filter(item => item.propName !== 'is_urgent_issues')
          console.log('dd', dd)
          const oldArr = _.groupBy(res.data, 'actInstId');//对象
          console.log('oldArr:', oldArr)
          let newArr = []
          Object.keys(oldArr).forEach(key=>{// 数组
            newArr.push({name:key,data:oldArr[key]})
          })
          console.log('console:', newArr)
          // 构造历史审批表单数据
          newArr.forEach(item => {
            const obj = item.data[0]
            let prop = {}
            console.log('item:', item)
            item.data.forEach(item => {
              if(item.propName && item.propName !== 'is_urgent_issues'){
                if(item.varType == 'double'){
                  prop[item.propName] = item.doubleValue
                } else if(item.varType == 'integer'){
                  prop[item.propName] = item.longValue
                } else if(item.varType == 'boolean'){
                  prop[item.propName] = item.longValue ? true : false
                } else if(item.varType == 'string'){
                  try {
                    prop[item.propName] = JSON.parse(item.propValue)
                  }catch (e) {
                    prop[item.propName] = item.propValue
                  }
                }
              }
            })
            if (JSON.stringify(prop) != '{}'){
              obj.formData = prop
              if(obj.taskDefKey == 'StartEvent_1') {
                this.startNodeForm = prop
              }
            }else{
              obj.isCurrNode = true
            }
            this.formList.push(obj)
          })
          this.currNode = this.formList.find(item => item.END_TIME_ == '')
          console.log('this.currNode:', this.currNode)
          // this.currNodeKey = this.currNode.taskDefKey

          // 获取每个节点表单配置信息，非当前审批节点的表单不可修改
          this.formList.forEach((item,index) =>{
            this.collapseList.push(index)
            result.forEach(node =>{
              if(item.taskDefKey == node.attributes.id){
                item.formDataConfig = JSON.parse(node.attributes['camunda:formKey'])
                if (!item.isCurrNode){
                  item.formDataConfig.list.forEach(temp => {
                    if (temp.type == 'grid'){
                      temp.columns.forEach(gg =>{
                        if(gg.list.length){
                          gg.list[0].options.disabled = true
                        }
                      })
                    } else {
                      temp.options.disabled = true
                    }
                  })
                } else if (item.taskName == '重填申请单'){
                  this.isRefill = true
                  item.formData = this.startNodeForm
                }
              }
            })
          })
          console.log('this.formList:', this.formList)
          this.tableLoating = false
          this.showHis = true
        })
      })
    }
  }
};
</script>

<style lang="less" scoped>
  #processApproveComponents .processTitle {
    font-weight: bold;
    font-size: 20px;
    margin-left: 20px;
    margin-top: 20px;
  }

  #processApproveComponents #headDetail .ant-form-item {
    margin-bottom: 0;
  }

  .textareaview {
    word-wrap: break-word;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
  .required::before {
    display: inline-block;
    margin-right: 4px;
    content: '*';
    font-family: SimSun;
    line-height: 1;
    font-size: 14px;
    color: #f5222d;
  }
  .el-card__body {
    background-color:#ffffff !important;
    color: #666 !important;
  }
  /deep/.el-textarea.is-disabled .el-textarea__inner{
    color:#666666 !important;
  }
  /deep/.el-radio__input.is-disabled+span.el-radio__label{
    color:#666666 !important;
  }
  /deep/.el-input.is-disabled .el-input__inner{
    color:#666666 !important;
  }
  .main_page{
    height: 100%;
  }
</style>
